package com.example.newsapp.view.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.newsapp.R;
import com.example.newsapp.view.adapter.VideoAdapter;
import com.example.newsapp.viewmodel.VideoViewModel;

public class VideoFragment extends Fragment {

    private VideoViewModel videoViewModel;
    private VideoAdapter videoAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private int currentPage = 0;
    private boolean isLoading = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_video, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化视图
        initViews(view);
        // 初始化ViewModel
        initViewModel();
        // 设置监听器
        setupListeners();
        // 加载数据
        loadVideos();
    }

    private void initViews(View view) {
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);

        // 设置RecyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        // 设置适配器
        videoAdapter = new VideoAdapter();
        recyclerView.setAdapter(videoAdapter);
    }

    private void initViewModel() {
        videoViewModel = new ViewModelProvider(this).get(VideoViewModel.class);

        // 观察视频数据
        videoViewModel.getVideoData().observe(getViewLifecycleOwner(), videoData -> {
            isLoading = false;
            swipeRefreshLayout.setRefreshing(false);

            if (videoData != null && videoData.getVideoList() != null && !videoData.getVideoList().isEmpty()) {
                if (currentPage == 0) {
                    // 刷新时直接设置数据
                    videoAdapter.setVideoList(videoData.getVideoList());
                } else {
                    // 加载更多时添加数据
                    videoAdapter.addVideoList(videoData.getVideoList());
                }
            } else {
                Toast.makeText(getContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
            }
        });

        // 观察错误信息
        videoViewModel.getErrorMessage().observe(getViewLifecycleOwner(), message -> {
            isLoading = false;
            swipeRefreshLayout.setRefreshing(false);
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        });
    }

    private void setupListeners() {
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            currentPage = 0;
            loadVideos();
        });

        // 上拉加载更多
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                    if (!isLoading
                            && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                            && firstVisibleItemPosition >= 0
                            && dy > 0) {
                        loadMore();
                    }
                }
            }
        });
    }

    private void loadVideos() {
        isLoading = true;
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }
        videoViewModel.getVideoList(currentPage);
    }

    private void loadMore() {
        isLoading = true;
        currentPage++;
        videoViewModel.getVideoList(currentPage);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (videoAdapter.getItemCount() == 0) {
            loadVideos();
        }
    }
}